package com.yuanxuzhen.androidmedia.audio;

import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/******
 * wav格式可以参考https://blog.csdn.net/qq_15255121/article/details/115168456
 *
 * ****/

public class WavPlayer {

    private static volatile WavPlayer instance;
    private AudioTrack mAudioTrack;
    private int audioFormat;
    private int buffersize;
    private ExecutorService executorService;
    private DataInputStream inputStream;
    private static final  int HEADER_SIZE = 44;
    private static final  int AUDIO_FORMAT_POSITION = 20;
    private static final  int AUDIO_NUM_CHANNEL_POSITION = 22;
    private static final  int AUDIO_BIT_PERSAMPLE_POSITION = 34;
    private static final  int AUDIO_SAMPLE_RATE_POSITION = 24;

    public class WavData{
        int channelMask = AudioFormat.CHANNEL_OUT_MONO;
        int sampleRate = 48000;
        int audioFormatEncodeing = AudioFormat.ENCODING_PCM_FLOAT;
    }

    private WavPlayer(){

    }

    public static WavPlayer getInstance(){
        if(instance == null){
            synchronized (WavPlayer.class){
                if(instance == null){
                    instance = new WavPlayer();
                }
            }
        }
        return instance;
    }



    public WavData getInfo(String path){
        WavData info = new WavData();
        try{
            int bitPerSample = 0;
            if(TextUtils.isEmpty(path)){
                return null;
            }
            File file = new File(path);
            if(!file.exists()){
                return null;
            }
            InputStream  wavInputStrem = new FileInputStream(file);
            /*wav头部总共占44个字节*/
            ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
            buffer.order(ByteOrder.LITTLE_ENDIAN); //格式 采样率 采样大小 声道数都是小端存储

            wavInputStrem.read(buffer.array(), buffer.arrayOffset(), buffer.capacity());
            buffer.rewind();
            buffer.position(AUDIO_FORMAT_POSITION);
            int format = buffer.getShort();
            Log.e("WavPlayer", "format = " + format);
            /*pcm播放*/
            if(format != 1){
                Log.e("WavPlayer", "format is not pcm");
                return null;
            }

            buffer.rewind();
            buffer.position(AUDIO_NUM_CHANNEL_POSITION);
            int channel = buffer.getShort();
            Log.e("WavPlayer", "channel="+channel);

            if(channel == 2){
                info.channelMask = AudioFormat.CHANNEL_OUT_STEREO;
            }


            buffer.rewind();
            buffer.position(AUDIO_SAMPLE_RATE_POSITION);
            info.sampleRate = buffer.getInt();
            Log.e("WavPlayer", "sampleRate="+info.sampleRate);


            buffer.rewind();
            buffer.position(AUDIO_BIT_PERSAMPLE_POSITION);
            bitPerSample = buffer.getShort();
            Log.e("WavPlayer", "bitPerSample="+bitPerSample);
            if(bitPerSample == 16){
                info.audioFormatEncodeing = AudioFormat.ENCODING_PCM_16BIT;
            }else if(bitPerSample == 8){
                info.audioFormatEncodeing = AudioFormat.ENCODING_PCM_8BIT;
            }else{
                info.audioFormatEncodeing = AudioFormat.ENCODING_PCM_FLOAT;
            }

            wavInputStrem.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return info;
    }



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void init(WavData data) {
        executorService = Executors.newCachedThreadPool();
        AudioFormat.Builder builder = new AudioFormat.Builder();
        builder.setChannelMask(data.channelMask)
                .setEncoding(data.audioFormatEncodeing)
                .setSampleRate(data.sampleRate);
        AudioFormat audioFormat = builder.build();

        buffersize = AudioTrack.getMinBufferSize(data.sampleRate,
                data.channelMask,
                data.audioFormatEncodeing);
        Log.e("yuanAudioTrack", "init buffersize=" + buffersize);
        AudioAttributes audioAttributes = (new AudioAttributes.Builder()).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
        mAudioTrack = new AudioTrack(
                audioAttributes,
                audioFormat,
                buffersize,
                AudioTrack.MODE_STREAM,
                AudioManager.AUDIO_SESSION_ID_GENERATE
        );

    }


    /**
     * 播放线程
     */
    Runnable recordRunnable = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            try {
                //设置线程的优先级
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
                byte[] tempBuffer = new byte[buffersize];
                int readCount = 0;
                while (inputStream.available() > 0) {
                    readCount= inputStream.read(tempBuffer);
                    if (readCount == AudioTrack.ERROR_INVALID_OPERATION || readCount == AudioTrack.ERROR_BAD_VALUE) {
                        continue;
                    }
                    if (readCount != 0 && readCount != -1) {//一边播放一边写入语音数据
                        //判断AudioTrack未初始化，停止播放的时候释放了，状态就为STATE_UNINITIALIZED
                        if(mAudioTrack.getState() == mAudioTrack.STATE_UNINITIALIZED){
                           return;
                        }
                        mAudioTrack.play();
                        mAudioTrack.write(tempBuffer, 0, readCount);
                    }
                }
                stopPlay();//播放完就停止播放
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };


    private void setPath(String path) throws Exception {
        File file = new File(path);
        inputStream = new DataInputStream(new FileInputStream(file));
        inputStream.skipBytes(HEADER_SIZE); //跳过WAV头部44个字节
    }

    public void stopPlay() {
        try {
            if (mAudioTrack != null) {
                if (mAudioTrack.getState() == AudioRecord.STATE_INITIALIZED) {//初始化成功
                    mAudioTrack.stop();//停止播放
                }
                if (mAudioTrack != null) {
                    mAudioTrack.release();//释放audioTrack资源
                }
                mAudioTrack = null;
            }
            if (inputStream != null) {
                inputStream.close();//关闭数据输入流
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startPlay(String path) {
        try {
            WavData wavData = getInfo(path);
            if(wavData == null){
                return;
            }
            init(wavData);
            setPath(path);
            executorService.execute(recordRunnable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
